import { computed, ref, unref, watchEffect } from 'vue'
import { isVideoFile } from '@/utils/index.js'

/**
 * 活动相关
 */
export const useActivity = (activity) => {
	// 活动信息
	const activityInfo = ref(activity)
	
	/**
	 * 多件多折排序
	 */
	const sortDiscount = (activeDiscount) => {
		if (activeDiscount && activeDiscount.length) {
			return activeDiscount.sort((a, b) => {
				return a.num - b.num
			})
		} else {
			return []
		}
	}

	/**
	 * 阶梯价格列表排序
	 */
	const sortStepPrices = (activeStepPrices) => {
		if (activeStepPrices && activeStepPrices.length) {
			return activeStepPrices.sort((a, b) => {
				return a.enrollNum - b.enrollNum
			})
		} else {
			return []
		}
	}
	
	// 更新活动信息
	const updateActivityInfo = (detail) => {
		activityInfo.value = detail
	}
	
	watchEffect(() => {
		if (activityInfo.value) {
			if (activityInfo.value.activeStepPrices) {
				sortStepPrices(activityInfo.value.activeStepPrices)
			}
			if (activityInfo.value.activeDiscount) {
				sortDiscount(activityInfo.value.activeDiscount)
			}
			if (activityInfo.value.content && !activityInfo.value.activeContents) {
				try {
					activityInfo.value.activeContents = JSON.parse(activityInfo.value.content)
				} catch(e) {}
			}
		}
	})
	
	/**
	 * 是否报名活动
	 * 活动类型(1-团购活动，2-报名活动，3-外部活动，4-团购+报名活动)
	 */
	const isSignUp = computed(() => {
		return activityInfo.value && activityInfo.value.enrollEnable == 1
	})
	
	// 是否外部活动
	const isLink = computed(() => {
		return activityInfo.value && activityInfo.value.activeType == 3
	})
	
	// 活动图片
	const photos = computed(() => {
		return activityInfo.value && activityInfo.value.activeImg && activityInfo.value.activeImg.split(',') || []
	})
	
	// 活动封面，首张图片
	const coverPicture = computed(() => {
		if (!photos.value || photos.value.length === 0) {
			return ''
		}
		for (let i = 0; i < photos.value.length; i++) {
			const item = photos.value[i]
			if (!isVideoFile(item)) {
				return item
			}
		}
		return ''
		// return photos.value.length ? photos.value[0] : ''
	})

	
	return {
		isSignUp,
		isLink,
		photos,
		coverPicture,
		sortStepPrices,
		sortDiscount,
		updateActivityInfo,
		activityInfo
	}
}